package org.microframework.cloud.files.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.util.StringUtils;

/**
 * MinIO初始化器
 */
@Slf4j
@Configuration
public class MinioInitializer {

    private final MinioClient minioClient;
    private final MinioProperties minioProperties;

    public MinioInitializer(MinioClient minioClient, MinioProperties minioProperties) {
        this.minioClient = minioClient;
        this.minioProperties = minioProperties;
    }

    /**
     * 应用程序启动后初始化存储桶
     */
    @EventListener(ApplicationReadyEvent.class)
    public void initBuckets() {
        if (!minioProperties.isEnabled()) {
            log.warn("MinIO服务已禁用，跳过存储桶初始化");
            return;
        }

        try {
            // 创建默认存储桶
            createBucketIfNotExists(minioProperties.getBucket().getDefault(), false);
            
            // 创建公共存储桶（允许匿名访问）
            createBucketIfNotExists(minioProperties.getBucket().getPublic(), true);
            
            // 创建临时存储桶
            createBucketIfNotExists(minioProperties.getBucket().getTmp(), false);
            
            log.info("MinIO存储桶初始化完成");
        } catch (Exception e) {
            log.error("初始化MinIO存储桶失败", e);
        }
    }

    /**
     * 创建存储桶并设置访问策略
     */
    private void createBucketIfNotExists(String bucketName, boolean isPublic) throws Exception {
        if (!StringUtils.hasText(bucketName)) {
            return;
        }

        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!exists) {
            log.info("创建存储桶: {}", bucketName);
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        if (isPublic) {
            // 设置公共读取权限
            String publicPolicy = """
                {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {"AWS": ["*"]},
                            "Action": ["s3:GetObject"],
                            "Resource": ["arn:aws:s3:::%s/*"]
                        }
                    ]
                }
                """.formatted(bucketName);
            
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(bucketName)
                    .config(publicPolicy)
                    .build());
            
            log.info("已设置存储桶 {} 为公共访问", bucketName);
        }
    }
} 